package com.gp.learn.ssm.base.core.security.service;

import com.gp.learn.ssm.base.core.security.model.OpenAuthority;
import com.gp.learn.ssm.base.core.security.model.OpenUser;
import com.gp.learn.ssm.base.core.security.model.UserAccount;
import com.gp.learn.ssm.base.core.security.model.UserInfo;
import com.gp.learn.ssm.base.system.service.BaseAccountService;
import com.gp.learn.ssm.common.enums.StateEnum;
import com.gp.learn.ssm.common.utils.ApiAssert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;

/**
 * UserDetailsService实现类
 */
@Service("UserDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {


    @Autowired
    private BaseAccountService baseAccountService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserAccount userAccount = baseAccountService.login(username);
        if (userAccount == null || userAccount.getAccountId() == null) {
            throw new UsernameNotFoundException("系统用户 " + username + " 不存在!");
        }
        if (StateEnum.DISABLE.getCode().equals(userAccount.getStatus())) {
            ApiAssert.failure("账户已禁用");
        }
        UserInfo userProfile = userAccount.getUserProfile();
        Integer status = userProfile.getStatus();
        if (StateEnum.DISABLE.getCode().equals(status)) {
            ApiAssert.failure("用户已禁用");
        }
        Long accountId = userAccount.getAccountId();
        Long userId = userAccount.getUserId();
        String account = userAccount.getAccount();
        String password = userAccount.getPassword();
        Collection<OpenAuthority> authorities = userProfile.getAuthorities();
        OpenUser openUser = new OpenUser(accountId, userId, account, password, true, true, true, authorities);
        //new User(account, password, authorities);
        return openUser;
    }
}
